<?php
/* 
 *出库管理 销售
 */
class GiftAction extends CommonAction {
    public function _filter(&$map) {
        //TODO
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
          if(strpos($key, ' ')) //高级搜索，仅搜索产品名称
            $map['_complex'] = A('Search')->search($key,'Gift','name');
          else{
            $where['name'] = array('like',"%".$key."%");//赠品名称

            $where['_logic'] = "or";
            $map['_complex'] = $where;
          }
        }
        

    }

    public function insert(){
         $model = 'Gift';
         $Model = M($model);
         $pid = $_POST['product_id'];
         if(!$pid)
            $this->error('请选择至少一个产品');
        if($pid != array_unique($pid))
          $this->error('您选择的产品存在重复，请去重后再操作！');

          $number = $_POST['number'];
          foreach ($number as $key => $value) {
            if($value <1 )
              $this->error("产品数量必须大于等于 1 ");
            continue;
          }
        if(false == $Model->create()) {
            $this->error($Model->getError());
        }
        if(false !== $list = $Model->add()) {
            $this->__process_enter_detail($list);
            $mod_field = getModelName ($list, $model);
            $msg = '新增 '.$model.': '.$mod_field.' (编号：'.$list.')';
            A('Action')->writeLog($msg,'新增',$model,$list);
            $this->assign ( 'jumpUrl', '__URL__' ); //return index list
            $this->success('添加成功');
        }
        else {
            $this->error('新增失败！');
        }
    }

    private function __process_enter_detail($list='')
    {
        $data =array(
                'goods_id'=>$_POST['product_id'],
                'name'=>$_POST['lot'], //产品批号作为商品标题代输入
                'price'=>$_POST['price'], //截止有效期
                'number'=>$_POST['number'],
                'gift_id'=>$list,
        );
        $len = count($data['goods_id']);
        $gift_detail = M('Gift_detail');
        $small_data = array();
        for ($i=0; $i < $len; $i++) { 
          $small_data = array(
            'goods_id' => $data['goods_id'][$i],
            'name'=>$data['name'][$i], //产品批号作为商品标题代输入
            'price'=>$data['price'][$i], //截止有效期
            'number'=>$data['number'][$i],
            'gift_id'=>$list,
            );
          $gift_detail->add($small_data);
        }
    }



    //增加产品赠品：根据特定产品，达到一定数量后即送赠品.只适用同一平台，不同平台同一客户不能赠送赠品
    public static function auto_add_gift($sale_no)
    {   $sale_model = M('Sale');
        $sale_no = trim($sale_no);
        $sale_view = $sale_model->getBySale_no($sale_no);
        if(empty($sale_view))
            return;
        $order_source_id = $sale_view['order_source_id']; //订单来源

        //如果已经赠送了赠品 或不是待发货状态，则跳过处理
        if($sale_view['got_gift'] == 1 || $sale_view['order_status'] != 2 )
          return; 
        
        $common_id = 0;
        $gift_rule = M('Gift_rule');
        
        $same_person_con = array(
                    'shipping_address_id' => $sale_view['shipping_address_id'],
                    'order_status' => 2, //待发货
                    'got_gift' => 0, //只允许未送赠品的订单
                    'status' => 0, //待审核的
                    'order_source_id' => $order_source_id, //保证同一平台的订单才合并赠送
                    );
        //合并所有同一人同地址的待发货订单
        $same_person_order_ids = $sale_model->where($same_person_con)->field('id')->findAll();
        $same_ids = array(); // 2 维同一人同类订单id

       foreach ($same_person_order_ids as $k => $v) {
         $same_ids[$k] = $v['id'];
       }
       $count_id = count($same_ids); //统计有同一人待发货订单
       $model = M('Sale_detail');
        if($order_source_id < 4){ //京卫系列订单通过out_number代替common_id
            if($count_id > 1 )
              $sql = "select sum(number) as sum_number,out_number from __TABLE__ where sale_id in (".implode(',', $same_ids).") group by out_number";
            else //只有一个时，加快速度
              $sql = "select sum(number) as sum_number,out_number from __TABLE__ where sale_id = ".$same_ids['0']." group by out_number";
       
        }else{ //使用唯一货品编码，需要转换成common_id
          if($count_id > 1 )
              $sql = "select sum(number) as sum_number,pt.common_id as out_number from __TABLE__ as de left join vm_product as pt on de.product_id = pt.id
               where sale_id in (".implode(',', $same_ids).") group by pt.common_id";
            else //只有一个时，加快速度
              $sql = "select sum(number) as sum_number,pt.common_id as out_number from __TABLE__  as de left join vm_product as pt on de.product_id = pt.id 
              where sale_id = ".$same_ids['0']." group by pt.common_id";
       
        }
         //重新归类common_id, 合并number
        $sale_details = $model->query($sql);
        foreach ($sale_details as $value) {
            //暂适用于药房网平台 TODO 如果是其他 平台，必须得到对应的common_id即产品的ID
            //$common_id = getModelName($value['product_id'] ,'Product','common_id' );    //产品ID
            $map = array(
                'order_source_id' => $sale_view['order_source_id'],
                'number' => array('elt', $value['sum_number']) //赠品数量小于或等于购买的总数量
                );

            if($order_source_id < 4){ //京卫系列订单通过out_number转换为common_product_id
                $jw_map = getPmap(1);
                $map['common_product_id'] = $jw_map[$value['out_number']];
            }else
                $map['common_product_id'] = $value['out_number']; //其他获取对应的common_product_id

            $rs = $gift_rule->where($map)->field('number,gift_id')->find(); 
            
            if($rs){ //符合赠品规则
                //需要赠送的赠品份数
                $gift_number_lot = intval( ( $value['sum_number'] / $rs['number'] ) );
                 
                if($count_id > 1 ){                  
                  $min_sid = min($same_ids);  //由于导入订单是按时间倒序排，最小ID即最大订单号
                  $max_sno = getModelName($min_sid,'Sale','sale_no');

                  A('Sale_detail')->gift_insert( $min_sid ,$max_sno,$rs['gift_id'],$gift_number_lot);
                  $sale_model ->where('id ='.$min_sid)->setField('got_gift',1); //已赠送赠品
                    //合并了以前的订单的,则加入备注
                    $msg = $count_id."单计满赠品,存入".$max_sno.",全部编号".implode(',', $same_ids);
                  
                    foreach ($same_ids as $v2) {
                      $remark_sql = "Update __TABLE__ set remark = concat(ifnull(remark,''),'".$msg."'),got_gift=1 where id = ".$v2;
                      $sale_model->query($remark_sql); //追加备注 同时置got_gift=1 表已送赠品
                    }
                }else{ //仅有一个，则存在当前
                    A('Sale_detail')->gift_insert($sale_view['id'],$sale_no,$rs['gift_id'],$gift_number_lot);
                    $sale_model->where('id ='.$sale_view['id'])->setField('got_gift',1); //置为已赠送赠品
                }
                    
                
            }
        }
    }

    //增加满赠赠品，满足多少金额就送赠品，限制在特定品牌范围内
    public static function add_over_gift($sale_no)
    {   $sale_model = M('Sale');
        $sale_no = trim($sale_no);
        $sale_view = $sale_model->getBySale_no($sale_no);

        //如果已经赠送了赠品 或不是待发货状态，则跳过处理
        if($sale_view['got_over_gift'] == 1 || $sale_view['order_status'] != 2 )
          return; 
        
        
        $gift_rule = M('Over_gift_rule');
        
        $same_person_con = array(
                    'shipping_address_id' => $sale_view['shipping_address_id'],
                    'order_status' => 2, //待发货
                    'got_over_gift' => 0, //只允许未送赠品的订单
                    'status' => 0, //待审核的
                    'order_source_id' => $sale_view['order_source_id'], //同一平台下方可赠送
                    );
        //合并所有同一人同地址的待发货订单
        $same_person_order_ids = $sale_model->where($same_person_con)->field('id')->findAll();
        $same_ids = array(); // 2 维同一人同类订单id

       foreach ($same_person_order_ids as $k => $v) {
         $same_ids[$k] = $v['id'];
       }
       
      $min_quota = $gift_rule->where('order_source_id = '.$sale_view['order_source_id'])->min('quota');
      $model = M('Sale_detail');
      $sale_map = "id in (".implode(',', $same_ids).")";
      $sum_total = $sale_model->where($sale_map)->sum('total');
      if(empty($sum_total) || $sum_total < $min_quota ) //如果值 为空，或小于最小满赠金额，直接返回不处理
        return ;
      else{
        //循环取同一平台下不同品牌组的总金额 TODO 存在同一平台如有多个满赠规则时,多次赠送的漏洞
        //同一平台下的多条满赠规则,默认为使用同一样的品牌限制规则.
        $brands = $gift_rule->where('order_source_id ='.$sale_view['order_source_id'])->getField('brand_id');
        $brand_id = unserialize( $brands);
          //统计同一品牌组的订单产品金额总计
       $sql = "select sum(de.total) as sum_total from vm_sale_detail as de  left join vm_product as pe
       on de.product_id = pe.id
        where de.sale_id in (".implode(',', $same_ids).")  and  pe.brand_id in (".implode(',', $brand_id).")";
        $sum_total = M()->query($sql);
        $sum_total = $sum_total['0']['sum_total'];
        if(empty($sum_total) )
            return;
        $right_quota = self::getRightQuota($sum_total,$sale_view['order_source_id']);
        if($right_quota == 0 )
            return;
        //找到最恰当的满赠规则
        $right_gift_rule = $gift_rule->where('order_source_id ='.$sale_view['order_source_id'].' and quota = '.$right_quota)->find();  
        //增加赠品
        $count_id = count($same_ids); //统计有同一人待发货订单
        if($count_id > 1 ){                  
            $min_sid = min($same_ids);  //由于导入订单是按时间倒序排，最小ID即最大订单号
            $max_sno = getModelName($min_sid,'Sale','sale_no');

            A('Sale_detail')->gift_insert( $min_sid ,$max_sno,$right_gift_rule['gift_id']);
            $sale_model ->where('id ='.$min_sid)->setField('got_over_gift',1); //已赠送赠品
              //合并了以前的订单的,则加入备注
              $msg = "*".$count_id."单计满赠,存入".$max_sno.",全部".implode(',', $same_ids);
            
              foreach ($same_ids as $v2) {
                    $remark_sql = "Update __TABLE__ set remark = concat(ifnull(remark,''),'".$msg."'),got_over_gift=1 where id = ".$v2;
                    $sale_model->query($remark_sql); //追加备注 同时置got_gift=1 表已送赠品
                  
              }
          }else{ //仅有一个，则存在当前
              A('Sale_detail')->gift_insert($sale_view['id'],$sale_no,$right_gift_rule['gift_id']);
              $sale_model->where('id ='.$sale_view['id'])->setField('got_over_gift',1); //置为已赠送赠品
          }

      }
    }

  /**
  **根据订单号，指定增加赠品 ，包括产品赠品规则及满赠规则
  ** @sale_no 订单数组
  **/
  public static function mass_add_gift($sale_nos =array())
  {
    if(count($sale_nos) < 1 )
      return;
    foreach ($sale_nos as $value) {
        self::auto_add_gift($value);
        self::add_over_gift($value);
    }
  }

  //自动 为系统中符合赠品 条件的订单 增加赠品，需要人工触发,也可机器自动执行，最好间隔时间长，这样合并订单绑定赠品准些
  public static function auto_mass_add_gift()
  {
      $gift_map = array(
        'order_status' => 2, //待发货
        '_string' => "got_gift = 0 or got_over_gift = 0", //未送赠品或满赠品的
        'status' => 0, //待审核的
      );
      $require_gift_orders = M('Sale')->where($gift_map)->field('sale_no')->findAll();
      $clear_orders = array();
      foreach ($require_gift_orders as $key => $value) {
          $clear_orders[$key] = $value['sale_no'];
      }
      self::mass_add_gift($clear_orders);
  }

  /*
  **返回相应的最近满赠区间
  **@ sum_total 符合相应品牌的所有订单总金额
  **@ order_source_id 订单来源
  **return right_quota
  **/
  public static function getRightQuota( $sum_total = 0,$order_source_id = 0 )
  {
    $gift_rules = M('Over_gift_rule')->where('order_source_id ='.$order_source_id)->field('quota')->findAll();
    sort($gift_rules); //升序排列
    $right_quota = 0;
    foreach ($gift_rules as $k => $v){
       $t = $sum_total - $v['quota']; 
       if($t < 0){
          return $right_quota;
          break;
       }
        
       if($t >= 0){
         $right_quota = $v['quota'];
       }
    }
    return $right_quota;
  }
   

}
?>
